The Developer Fastlane

« 365 days to become a developer » challenge

PHP: Page views meter

November 12, 2020

Instructions & result

We want to create a counter that calculates the number of pages viewed on the website since its creation.
Important: we want to be able to display several times the counter without incrementing the visits number.
That's why i'll need to seperate functions so that :
  • first one is dedicated to increment the file each time a page is viewed: it is included in footer.php
  • second one is to display the number wherever we need as a snippet of code, whitout changing the count.
Result
Click on one of the images above to access the exercise's website

Code

Steps

  1. Verify that the counter.txt file exists (condition)
  2. If it doesn't not exist (false):
    • create it (file_put_contents)
    • fill it with the value "1"
  3. If it exists (true):
    • read the file's content (file_get_contents)
    • convert this value into an integer and add 1 to it
    • write the file with this new value (file_put_contents with no flags to replace the content)
  4. Create a snippet of code to display the counter

footer.php

This code increments the counter .txt file each time a page is viewed. That's why we need to put it in footer.php, which is part of every pages of the website.
Code
require_once (dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'functions_counters.php'); 
    // Call functions_counters.php   
counter_page_views_db(); // Define database path
counter_page_views_increment(); // Add 1 to database for every new page view
counter_page_views_snippet(); // Display counter as a string

functions_counters.php

Core functions
Code
<?php

// page views

function counter_page_views_db(): string 
{
    $db = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'php-playground' . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'counter_page-views' . DIRECTORY_SEPARATOR . 'total.txt';
    return $db;
}
function counter_page_views_increment(): void
{
    $db = counter_page_views_db();
    if (file_exists($db)) {
        $views = (int)file_get_contents($db);
        $views++;
    } else {
        $views = 1;
    }
    file_put_contents($db, $views);
}
function counter_page_views_snippet(): void
{
    $db = counter_page_views_db();
    $counter_total = file_get_contents($db);
    $line = "<b>$counter_total</b> page view";
    if ($counter_total !== 1) { $line .= 's'; }; // Use plural only if several views
    echo $line;
}
© 2020 - Edouard Proust | The Developer Fastlane